package com.cqc.jdk8.Jnio.file;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;

/**
 * @author cui
 * @description Path类练习
 * @date 2022/6/9
 **/
public class PathTest {

    //构建 Path对象
    @Test
    public void f1() {
        Path path1 = Paths.get("D:/a.txt");
        Path path2 = Paths.get("D:/AA", "AC", "B.txt");//拼接路径，没有AC目录也不报错  D:\AA\AC\B.txt
        System.out.println("path1.toString()=" + path1.toString());//D:\a.txt
        System.out.println("path2.toString()=" + path2.toString());//D:\AA\A.txt

        URI uri = URI.create("file:///D:/AA/A.txt");
        Path path3 = Paths.get(uri);
        System.out.println("path3.toString()=" + path3.toString());//D:\AA\A.t

        Path path4 = FileSystems.getDefault().getPath("D:/a.txt");
        System.out.println("path4.toString()=" + path4.toString());//D:\AA\A.t
    }


    //File Path URI
    @Test
    public void f2() {
        File file1 = new File("D:/a.txt");
        Path path1 = file1.toPath();
        File file2 = path1.toFile();
        URI uri1 = path1.toUri();
        URI uri = file1.toURI();
    }


    //创建文件
    @Test
    public void f3() throws IOException {
        //文件是否存在
//        Path path = Paths.get("D:/b2.txt");
//        if(!Files.exists(path)){
//            Path path1 = Files.createFile(path);//目录不存在的话，会报错 java.nio.file.NoSuchFileException: D:\AB\b2.txt
//            System.out.println("path1.toString()="+path1.toString());
//        }

        //目录是否存在
        System.out.println(Files.exists(Paths.get("D:\\temp\\A\\B\\C\\")));
    }

    //读取文件
    @Test
    public void f4() throws IOException {
//        Path path = Paths.get("D:/a.txt");//文件必须是U8编码，否则报错 java.nio.charset.MalformedInputException: Input length = 1
        Path path = Paths.get("D:/a.txt");
        BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);//默认也是U8编码
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }

    //写入文件
    @Test
    public void f5() throws IOException {
        Path path = Paths.get("D:/a.txt");
        //StandardOpenOption.APPEND  追加文本内容，默认是清空内容重新写入TRUNCATE_EXISTING
        BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
        writer.write("王五,18,深圳市");
        writer.newLine();
        writer.flush();
        writer.close();
    }


}
